package rabbitmq.test.dlx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class DlxDeclare {
    private Channel channel;
    @Before
    public void init(){
        //1.创建长连接 提供属性(ip,port,username,password,virtualHost)
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.8.100");
        factory.setPort(5672);//TCP协议端口
        factory.setUsername("admin");
        factory.setPassword("123456");
        factory.setVirtualHost("/");
        try{
            Connection connection = factory.newConnection();
            //2.从长连接赋值短链接
            channel=connection.createChannel();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("创建连接失败");
        }
    }
    //业务交换机
    public static final String BIZ_EX="biz_ex";//FANOUT
    public static final String BIZ_QUEUE="biz_queue";
    public static final String DLX_EX="dlx_ex";//DIRECT
    public static final String DLX_QUEUE="dlx_queue";
    public static final String DLX_ROUTING_KEY="dlx_routing_key";
    @Test
    public void declareDlx() throws Exception{
        //声明业务交换机 和死信交换机
        channel.exchangeDeclare(BIZ_EX,"fanout");
        channel.exchangeDeclare(DLX_EX,"direct");
        //声明死信队列 没有额外的特殊属性
        channel.queueDeclare(DLX_QUEUE,false,false,false,null);
        //声明业务队列 提供多个map属性 ttl max-length dlex dlrk
        Map<String,Object> args=new HashMap<>();
        //消息超时时间
        args.put("x-message-ttl",1000*60);
        //队列最大长度
        //args.put("x-max-length",5);
        //可以在最大长度的基础上 设置溢出行为 不设置默认drop-head
        //指定业务队列产生死信 的死信交换机
        args.put("x-dead-letter-exchange",DLX_EX);
        //指定业务队列产生死信 的死信路由key
        args.put("x-dead-letter-routing-key",DLX_ROUTING_KEY);
        channel.queueDeclare(BIZ_QUEUE,false,false,false,args);
        //处理两组绑定关系
        channel.queueBind(BIZ_QUEUE,BIZ_EX,"");
        channel.queueBind(DLX_QUEUE,DLX_EX,DLX_ROUTING_KEY);
    }

}
